package cn.qingyun.gis.modules.init.utils;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.metadata.CellExtra;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.read.listener.ReadListener;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;

@Slf4j
public class ExcelTool {
    private ExcelTool() {
        throw new IllegalStateException("Utility class");
    }

    public static <T> void readSheet(MultipartFile file, Integer sheetNo, Class<?> clazz, Consumer<List<T>> consumer) {
        try {
            List<T> records = Lists.newArrayList();
            EasyExcelFactory.read(file.getInputStream()).sheet().sheetNo(sheetNo).head(clazz).registerReadListener(new ReadListener<T>() {
                @Override
                public void onException(Exception exception, AnalysisContext context) throws Exception {
                    ReadListener.super.onException(exception, context);
                }

                @Override
                public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
                    ReadListener.super.invokeHead(headMap, context);
                }

                @Override
                public void invoke(T data, AnalysisContext context) {
                    records.add(data);
                }

                @Override
                public void extra(CellExtra extra, AnalysisContext context) {
                    ReadListener.super.extra(extra, context);
                }

                @Override
                public void doAfterAllAnalysed(AnalysisContext context) {
                    if (CollUtil.isNotEmpty(records) && Objects.nonNull(consumer)) {
                        consumer.accept(records);
                    }
                }

                @Override
                public boolean hasNext(AnalysisContext context) {
                    return ReadListener.super.hasNext(context);
                }
            }).doReadSync();
        } catch (IOException e) {
            log.error("数据解析异常", e);
        }
    }

}
